const { startProcess, qiniuUpload }  = require('../libs/utils'),
      { addSliderData } = require('../services/Slider'),
      { addAgencyInfo } = require('../services/AgencyInfo'),
      { addRecomCourse } = require('../services/RecomCourse'),
      { addCollection } = require('../services/Collection'),
      { addTeacherData } = require('../services/Teacher'),
      { addStudentData } = require('../services/Student'),
      { addCourseTabData } = require('../services/CourseTab'),
      { addCourseData } = require('../services/Course'),
      { addAboutus } = require('../services/Aboutus'),
      { qiniu } = require('../config/config'),
      { CRAWLER } = require('../config/error_config'),
      { returnInfo } = require('../libs/utils');

class Crawler {

    //这个方法是用来接收我们后台管理中请求过来的，this[field]();就能执行相对应的方法去爬取数据
//     async crawlAction (ctx, next) {
//         let { apiName } = ctx.request.body;
//         // const apiName = 'crawlAboutus';
//         switch (apiName) {
//             case 'crawl_slider_data':
//                 apiName = 'crawlSliderData';
//                 break;
//             case 'crawl_agency_info':
//                 apiName = 'crawlAgencyInfo';
//                 break;
//             case 'crawl_recom_course':
//                 apiName = 'crawlRecomCourse';
//                 break;
//             case 'crawl_collection':
//                 apiName = 'crawlCollention';
//                 break;
//             case 'crawl_teacher':
//                 apiName = 'crawlTeacher';
//                 break;
//             case 'crawl_student':
//                 apiName = 'crawlStudent';
//                 break;
//             case 'crawl_course_tab':
//                 apiName = 'crawlCourseTab';
//                 break;
//             case 'crawl_course_data':
//                 apiName = 'crawlCourseData';
//                 break;
//             case 'crawl_aboutus':
//                 apiName = 'crawlAboutus';
//                 break;
        
//             default:
//                 break;
//         }

//         const result = await Crawler.prototype[apiName](ctx, next);
      
//         ctx.body = result;
//     }
//由于代码改造，以上代码已经弃用



    //爬取轮播图
    async crawlSliderData(ctx, next) {
        const retData = await new Promise((resolve) => {
            startProcess({
                path: '../crawlers/slider',
                async message (data) {//进到message这里证明数据爬取成功了，上传七牛，上传数据库都在这里面进行
                    data.map(async item => {
                        if (item.imgUrl && !item.imgKey) {//因为我们要给图片另起名称，所以这个imgKey要为空才行
                            try {//这是网络传输，有可能会报错，所以要try cacth 一下
                                 //上传成功了内部返回的是一个{ key }给这个imgData
                                const imgData = await qiniuUpload({//上传七牛
                                    url: item.imgUrl,
                                    bucket: qiniu.bucket.tximg.bucket_name,
                                    ext: '.jpg'
                                });
    
                                if (imgData.key) {
                                    item.imgKey = imgData.key;
                                }
    
                                // console.log(item);
                                
                                const result = await addSliderData(item);
    
                                if (result) {
                                    console.log('Data create OK');
                                } else {
                                    console.log('Data create failed');
                                }
                            } catch (error) { 
                                // throw new Error(error);
                                console.log(error);
                            }
                        }
                    });
    
                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
                async exit (code) {
                    console.log(code);
                },
                async error (error) {
                    console.log(error);
                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })
        
        ctx.body = await retData;
    }

    //爬取首页机构信息
    async crawlAgencyInfo (ctx, next) {
        const retData = await new Promise((resolve) => {
        startProcess({
            path: '../crawlers/agencyInfo',
            async message (data) {
                if (data.logoUrl && !data.logoKey) {
                    try {
                        //上传成功了内部返回的是一个{ key }
                        const logoData = await qiniuUpload({//上传七牛
                            url: data.logoUrl,
                            bucket: qiniu.bucket.tximg.bucket_name,
                            ext: '.jpg'
                        });
    
                        if(logoData.key) {
                            data.logoKey = logoData.key
                        }
                        // console.log(data);
    
                        const result = await addAgencyInfo(data);

                        if (result) {
                            console.log('Data create OK!')
                        } else {
                            console.log('Data create failed');
                        }
                    } catch (error) {
                        // throw new Error(error);
                        console.log(error);
                    }
                }

                resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
            },
            async exit (code) {
                console.log(code);
            },
            async error (error) {
                console.log(error);
                resolve(returnInfo(CRAWLER.CRAWL_FAILED));
            }
        })
       })

       ctx.body = await retData;
    }

    //爬取'推荐课程'
    async crawlRecomCourse (ctx, next) {
       const retData = await new Promise(resolve => {
        startProcess({
            path: '../crawlers/recomCourse',
            async message (data) {
                
                data.map(async item => {
                    try {//这是网络传输，有可能会报错，所以要try cacth 一下
                        if (item.posterUrl && !item.posterKey) {//因为我们要给图片另起名称，所以这个imgKey要为空才行
                            //上传成功了内部返回的是一个{ key }给这个imgData
                            const posterData = await qiniuUpload({//上传七牛
                                url: item.posterUrl,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });

                            if (posterData.key) {
                                item.posterKey = posterData.key;
                                // console.log('poster:' + item.posterKey);
                            }
                        }

                        if (item.teacherImg && !item.teacherImgKey) {
                            const teacherImgData = await qiniuUpload({
                                url: item.teacherImg,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });

                            if (teacherImgData.key) {
                                item.teacherImgKey = teacherImgData.key;
                                // console.log('teacher:' + item.posterKey);
                            }
                        }

                        // console.log(data);
                        const result = await addRecomCourse(item);
                        if (result) {
                            console.log('Data create OK!')
                        } else {
                            console.log('Data create failed!')
                        }

                    } catch (error) { 
                        // throw new Error(error);
                        console.log(error);
                    }
                });

                resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
            },
            async exit (code) {
                console.log(code);
            },
            async error (error) {
                console.log(error);

                resolve(returnInfo(CRAWLER.CRAWL_FAILED));
            }

        })
       })

       ctx.body = await retData;
    }

    //'收集课程'
    async crawlCollention (ctx, next) {
       const retData = await new Promise(resolve => {
        startProcess({
            path: '../crawlers/collection',
            async message (data) {
                data.map(async item => {
                    if (item.posterUrl && !item.posterKey) {
                        try {//这是网络传输，有可能会报错，所以要try cacth 一下
                             //上传成功了内部返回的是一个{ key }给这个imgData
                            const posterData = await qiniuUpload({//上传七牛
                                url: item.posterUrl,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });

                            if (posterData.key) {
                                item.posterKey = posterData.key;
                            }
                            console.log(item);
                            
                            const result = await addCollection(item);

                            if (result) {
                                console.log('Data create OK');
                            } else {
                                console.log('Data create failed');
                            }
                        } catch (error) { 
                            // throw new Error(error);
                            console.log(error);
                        }
                    }
               })

               resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
            },
            async exit (code) {
                console.log(code);
            },
            async error (error) {
                console.log(error);

                resolve(returnInfo(CRAWLER.CRAWL_FAILED));
            }

        })
       })

       ctx.body = await retData;
    }

    //明星老师
    async crawlTeacher (ctx, next) {
        const retData = await new Promise( resolve => {
            startProcess({
                path: '../crawlers/teacher',
                async message (data) {
                    data.map(async item => {
                        if (item.teacherImg && !item.teacherImgKey) {
                            try {
                                //上传成功了内部返回的是一个{ key }
                                const imgData = await qiniuUpload({//上传七牛
                                    url: item.teacherImg,
                                    bucket: qiniu.bucket.tximg.bucket_name,
                                    ext: '.jpg'
                                });
            
                                if(imgData.key) {
                                    item.teacherImgKey = imgData.key
                                }
                                // console.log(item);
            
                                const result = await addTeacherData(item);
        
                                if (result) {
                                    console.log('Data create OK!')
                                } else {
                                    console.log('Data create failed');
                                }
                            } catch (error) {
                                // throw new Error(error);
                                console.log(error);
                            }
                        }
                    })

                    resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
                },
    
                async exit (code) {
                    console.log(code);
                },
    
                async error (error) {
                    console.log(error);

                    resolve(returnInfo(CRAWLER.CRAWL_FAILED));
                }
            })
        })

        ctx.body = await retData;
    }

    //优秀学员
    async crawlStudent (ctx, next) {
       const retData = await new Promise( resolve => {
        startProcess({
            path: '../crawlers/student',
            async message (data) {
                data.map(async item => {
                    if (item.studentImg && !item.studentImgKey) {
                        try {
                            //上传成功了内部返回的是一个{ key }
                            const studentData = await qiniuUpload({//上传七牛
                                url: item.studentImg,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });
        
                            if(studentData.key) {
                                item.studentImgKey = studentData.key
                            }
                            // console.log(item);
        
                            const result = await addStudentData(item);
    
                            if (result) {
                                console.log('Data create OK!')
                            } else {
                                console.log('Data create failed');
                            }
                        } catch (error) {
                            // throw new Error(error);
                            console.log(error);
                        }
                    }

                })

                resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
            },
            async exit (code) {
                console.log(code);
            },
            async error (error) {
                console.log(error);

                resolve(returnInfo(CRAWLER.CRAWL_FAILED));
            }
        })
       })

       ctx.body = await retData;
    }

    //课程tab
    async crawlCourseTab (ctx, next) {
       const retData = await new Promise( resolve => {
        startProcess({
            path: '../crawlers/courseTab',
            async message (data) {
                if (data) {
                    data.map(async item => {
                        const result = await addCourseTabData(item);
     
                        if (result) {
                            console.log('Data create OK')
                        } else {
                            console.log('Data create failed')
                        }
                     })
                };

                resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
            },
            async exit (code) {
                console.log(code);
            },
            async error (error) {
                console.log(error);

                resolve(returnInfo(CRAWLER.CRAWL_FAILED));
            }
        })
       })

       ctx.body = await retData;
    }

    //全部课程
    async crawlCourseData (ctx, next) {
       const retData = await new Promise( resolve => {
        startProcess({
            path: '../crawlers/course',
            async message (data) {
                console.log('data:'+data);
                data.map(async item => {
                    if (item.posterUrl && !item.posterKey) {
                        try {
                            //上传成功了内部返回的是一个{ key }
                            const posterData = await qiniuUpload({//上传七牛
                                url: item.posterUrl,
                                bucket: qiniu.bucket.tximg.bucket_name,
                                ext: '.jpg'
                            });
        
                            if(posterData.key) {
                                item.posterKey = posterData.key
                            }
                            // console.log(item);
        
                            const result = await addCourseData(item);
    
                            if (result) {
                                console.log('Data create OK!')
                            } else {
                                console.log('Data create failed');
                            }
                        } catch (error) {
                            // throw new Error(error);
                            console.log(error);
                        }
                    }

                })

                resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
            },
            async exit (code) {
                console.log(code);
            },
            async error (error) {
                console.log(error);

                resolve(returnInfo(CRAWLER.CRAWL_FAILED));
            }
        })
       })

       ctx.body = await retData;
    }

    //关于我们
    async crawlAboutus (ctx, next) {
       const retData = await new Promise( resolve => {
        startProcess({
            path: '../crawlers/aboutus',
            async message (data) {
                if (data.posterUrl && !data.posterKey) {
                    try {
                        //上传成功了内部返回的是一个{ key }
                        const posterData = await qiniuUpload({//上传七牛
                            url: data.posterUrl,
                            bucket: qiniu.bucket.tximg.bucket_name,
                            ext: '.jpg'
                        });
    
                        if(posterData.key) {
                            data.posterKey = posterData.key
                        }
                        // console.log(data);
    
                        const result = await addAboutus(data);

                        if (result) {
                            console.log('Data create OK!')
                        } else {
                            console.log('Data create failed');
                        }
                    } catch (error) {
                        // throw new Error(error);
                        console.log(error);
                    }
                }

                resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
            },
            async exit (code) {
                console.log(code);
            },
            async error (error) {
                console.log(error);

                resolve(returnInfo(CRAWLER.CRAWL_FAILED));
            }
        })
       })

       ctx.body = await retData;
    }

}

module.exports = new Crawler();